package main;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import cz.ctu.guiproject.server.resources.Constants;

public class Loader {
	
	public Loader() {
		scanFolder(Constants.CURRENT_DIR);
	}

	private void loadJar(String jarFileName) {
		JarFile jarFile = null;
		try {
			jarFile = new JarFile(jarFileName);
			Enumeration<?> e = jarFile.entries();

			URL[] urls = { new URL("jar:file:" + jarFileName + "!/") };
			URLClassLoader cl = URLClassLoader.newInstance(urls);

			List<Class<?>> classList = new ArrayList<>();

			while (e.hasMoreElements()) {
				JarEntry je = (JarEntry) e.nextElement();
				if (je.isDirectory() || !je.getName().endsWith(Constants.CLASS_EXT)) {
					continue;
				}
				// -6 because of .class
				String className = je.getName().substring(0,
						je.getName().length() - 6);
				className = className.replace(Constants.FORWARD_SLASH, Constants.DOT);
				Class<?> c = cl.loadClass(className);
				classList.add(c);
			}
			
			// create new instance
			for(Class<?> clazz : classList) {
				try {
					Object a = clazz.newInstance();
					System.out.println(a.toString());
				} catch (InstantiationException e1) {
					e1.printStackTrace();
				} catch (IllegalAccessException e1) {
					e1.printStackTrace();
				}
			}
			
		} catch (IOException | ClassNotFoundException e) {
			System.err.println(e.getMessage());
		}
	}

	/**
	 * Searches the content of the current folder TODO recursively search
	 * through all subdirectories
	 * 
	 * @param baseFolder
	 *            Where the search begins
	 */
	private void scanFolder(String baseFolder) {
		final File f = new File(baseFolder);
		final List<String> folderNames = new ArrayList<>(Arrays.asList(f.list()));
		final Iterator<String> it = folderNames.iterator();
		while (it.hasNext()) {
			final String folderName = it.next();
			if (!folderName.endsWith(Constants.JAR_EXT)) {
				it.remove();
			} else {
				loadJar(folderName);
			}
		}
		System.out.println(folderNames);
	}

	public static void main(String[] args) {
		new Loader();
	}
}
